package vip.wangwenhao.sso.config.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;
import vip.wangwenhao.common.util.BeanUtils;
import vip.wangwenhao.sso.service.UserService;
import vip.wangwenhao.sso.constants.Oauth2Constants;
import vip.wangwenhao.sso.dto.UserDTO;

/**
 * @author wwh
 * @date 2019年12月30日 16:19
 */

public class CustomJwtAccessTokenConverter extends JwtAccessTokenConverter {

    @Autowired
    private UserService userService;

    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {

        KeyStoreKeyFactory keyStoreKeyFactory = new KeyStoreKeyFactory(new ClassPathResource(Oauth2Constants.JWT_FILE_NAME),
                Oauth2Constants.JWT_SECRET.toCharArray());
        this.setKeyPair(keyStoreKeyFactory.getKeyPair(Oauth2Constants.JWT_KEY_PAIR));

        OAuth2AccessToken oAuth2AccessToken = super.enhance(accessToken, authentication);
        Authentication userAuthentication = authentication.getUserAuthentication();
        if (userAuthentication != null) {
            String username = userAuthentication.getName();
            UserDTO userDTO = userService.queryByUsername(username);
            DefaultOAuth2AccessToken defaultOAuth2AccessToken = ((DefaultOAuth2AccessToken) oAuth2AccessToken);
            defaultOAuth2AccessToken.setAdditionalInformation(BeanUtils.beanToMap(userDTO));
        }
        return oAuth2AccessToken;
    }
}